﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.ServiceModel.Dispatcher;

namespace UFIDA.U9.WSS.ProxyService.Behavior.Endpoint
{
    /// <summary>
    ///     上下文扩展
    /// </summary>
    public class U9ContextEndpointBehaviorExtension : BehaviorExtensionElement
    {
        #region BehaviorExtensionElement

        public override Type BehaviorType
        {
            get { return typeof(U9ContextEndpointBehavior); }
        }

        protected override object CreateBehavior()
        {
            List<IDispatchMessageInspector> inspectors = new List<IDispatchMessageInspector>();
            foreach (BehaviorExtensionElement childBehavior in Behavior)
            {
                IDispatchMessageInspector inspector =
                    Activator.CreateInstance(childBehavior.BehaviorType) as IDispatchMessageInspector;
                if (inspector == null)
                    throw new Exception("behavior must inherit IDispatchMessageInspector");
                inspectors.Add(inspector);
            }

            return new U9ContextEndpointBehavior(inspectors, ContextType, ContextNeedUserPassword);
        }

        [ConfigurationProperty("behavior", IsDefaultCollection = false)]
        public EndpointBehaviorElement Behavior
        {
            get
            {
                EndpointBehaviorElement behavior =
                    (EndpointBehaviorElement) base["behavior"];
                return behavior;
            }
        }

        [ConfigurationProperty("contextType", DefaultValue = "", Options = ConfigurationPropertyOptions.None)]
        public string ContextType
        {
            get { return this["contextType"] != null ? this["contextType"] as string : string.Empty; }
        }

        /// <summary>
        ///     上下文是否需要密码
        /// </summary>
        [ConfigurationProperty("contextNeedUserPassword", DefaultValue = false,
            Options = ConfigurationPropertyOptions.None)]
        public bool ContextNeedUserPassword
        {
            get
            {
                if (this["contextNeedUserPassword"] == null ||
                    this["contextNeedUserPassword"].ToString() == string.Empty)
                    return false;
                return bool.Parse(this["contextNeedUserPassword"].ToString());
            }
        }

        #endregion
    }
}